/* eslint-disable max-len */
/* eslint-disable camelcase */
/* eslint-disable react-hooks/rules-of-hooks */
/* eslint-disable jsx-a11y/no-noninteractive-element-interactions */
/* eslint-disable @typescript-eslint/no-unused-expressions */
/* eslint-disable jsx-a11y/no-static-element-interactions */
/* eslint-disable jsx-a11y/click-events-have-key-events */
import React, {
  useMemo, useCallback, useEffect,
} from 'react';
import {
  Tooltip, Modal, DataSet, CheckBox,
} from 'choerodon-ui/pro';
import { Popover } from 'choerodon-ui';
import {
  Action, Choerodon,
} from '@choerodon/master';
import { observer } from 'mobx-react-lite';
import {
  useParams, useHistory, useLocation,
} from 'react-router';
// @ts-ignore
import queryString from 'query-string';
import map from 'lodash/map';
import eventStopProp from '@/utils/eventStopProp';
import TreeItemName from '@/components/treeitem-name';
// eslint-disable-next-line import/order
import moment from 'moment';
import UserInfo from '@/components/userInfo/avatar';
import TimePopover from '@/components/timePopover';
import AduitModal from '../audit-modal';
import StatusTag from '../../../deployment-list/components/StatusTag';
import { timeConverts } from '@/utils/index';
import { useDetailStore } from '../../stores/index';
import {
  retry, cancelExecute, persionCheck, checkStatus,
} from './service';
import './index.less';

interface Iprops{
  siderDs:DataSet,
  prefixCls:string,
}
const Index:React.FC<Iprops> = (props:Iprops) => {
  const { siderDs, prefixCls } = props;
  const {
    dyDetailStore,
    recordDetailDs,
    pipDetailDs,
    realName,
    projectId,
  } = useDetailStore();
  const { search } = useLocation();
  const { recordId, audit_flag } = queryString.parse(search);
  const prefix = 'deployment-content-sider-list';
  const dataSource = siderDs.toData();
  const maps:any = new Map([
    ['manual', '手动触发'],
    ['schedule', '定时触发'],
    ['app_version', '应用服务版本触发'],
    ['api', 'api触发'],
  ]);
  const timePopoverStyle = useMemo(() => ({
    fontSize: '.12rem',
    color: 'rgba(58,52,95,0.65)',
    margin: '0 0 0 0',
    flexShrink: '0',
    paddingLeft: '4px',
  }), [recordId, audit_flag]);
  // 头部按钮整体刷新重置页面
  const handleClick = (index:number, id:string) => () => {
    dyDetailStore.setIndex(index);
    dyDetailStore.setFlag(1);
    dyDetailStore.setRecordId(id);
    recordDetailDs.setQueryParameter('id', id);
    recordDetailDs.query();
  };
  const getStyle = (index:number) => (
    dyDetailStore.getIndex === index ? {
      background: '#f5f6fa',
      borderLeft: '4px solid #6887e8',
    } : {}
  );
  // 刷新
  const refresh = (id:string) => {
    siderDs.query();
    recordDetailDs.setQueryParameter('id', id);
    recordDetailDs.query();
    pipDetailDs.query();
  };
  // 渲染三点操作 根据状态显示相对应的操作
  const renderAction = useCallback((item:any) => {
    const { id, pipelineAuditInfo, name } = item || {};
    let actionData:object[] = [];
    switch (item.status) {
      case 'created':
      case 'running':
      case 'pending':
        actionData = [
          {
            service: ['choerodon.code.project.deploy.continuous-deployment.ps.cancel'],
            text: '取消执行',
            action: () => handleCancelExecute(id),
          },
        ];
        break;
      case 'not_audit':
        if (pipelineAuditInfo && pipelineAuditInfo.length > 0) {
          if (pipelineAuditInfo.length === 1) {
            const jobName = pipelineAuditInfo[0]?.jobName || '';
            const jobRecordId = pipelineAuditInfo[0]?.jobRecordId || '';
            actionData.push({
              service: [
                'choerodon.code.project.deploy.continuous-deployment.ps.audit',
              ],
              text: '人工审核',
              action: () => Modal.open({
                key: Modal.key(),
                title: '人工审核',
                children: <AduitModal
                  name={name}
                  taskRecordId={jobRecordId}
                  onClose={refresh}
                  jobName={jobName}
                  checkStatus={checkStatus}
                  persionCheck={persionCheck}
                />,
                movable: false,
              }),
            });
          } else {
            actionData.push({
              service: [
                'choerodon.code.project.deploy.continuous-deployment.ps.audit',
              ],
              text: (
                <Popover
                  overlayClassName="7ncd-action-menu-item-content-audit-popover"
                  content={
                       pipelineAuditInfo?.map(({ jobName, jobRecordId }:any, index:number) => (
                         // eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions
                         <p
                           className="c7ncd-action-menu-items-content-audit-item"
                           onClick={() => Modal.open({
                             key: Modal.key(),
                             title: '人工审核',
                             children: <AduitModal
                               name={name}
                               taskRecordId={jobRecordId}
                               onClose={refresh}
                               jobName={jobName}
                               checkStatus={checkStatus}
                               persionCheck={persionCheck}
                             />,
                             movable: false,
                           })}
                         >
                           {jobName}
                         </p>
                       ))
                      }
                  placement="rightTop"
                  trigger="hover"
                >
                  人工审核
                </Popover>
              ),
            });
          }
        } else {
          actionData = [];
        }
        break;
      case 'failed':
      case 'canceled':
        actionData = [
          {
            service: ['choerodon.code.project.deploy.continuous-deployment.ps.retry'],
            text: '重试',
            action: () => handleRetry(id),
          },
        ];
        break;
      default:
        break;
    }
    return actionData.length !== 0 ? <Action data={actionData} onClick={eventStopProp} />
      : <span style={{ width: 24 }} />;
  }, []);
  /**
   * 流水线记录操作
   */
  // 取消执行
  const handleCancelExecute = async (id:string) => {
    try {
      const res = await cancelExecute(projectId, id);
      refresh(id);
    } catch (e) {
      Choerodon.handleResponseError(e);
    }
  };
  // 重试
  const handleRetry = async (id:string) => {
    try {
      const res = await retry(projectId, id);
      refresh(id);
    } catch (e) {
      Choerodon.handleResponseError(e);
    }
  };
  // 获取持续时间
  const getDurationTime = (finish:any, start:string) => {
    if (!finish || !start) {
      return '-';
    }
    return timeConverts(moment(finish).diff(moment(start), 'seconds'));
  };
  // 待我审核查询
  const handleChange = (value:any, oldvalue:any) => {
    dyDetailStore.setAuditFlag(value);
    dyDetailStore.setIndex(-100);
    dyDetailStore.setFlag(0);
    siderDs.setQueryParameter('audit_flag', value);
    siderDs.query();
  };
  return (
    <>
      {dataSource.length === 0 ? <div style={{ marginTop: '20px', textAlign: 'center' }}>暂无历史运行记录</div>
        : dataSource.map((item:any, index:number) => (
          <div className={prefix} key={item.id}>
            <div className={`${prefix}-column`}>
              {index === 0 ? (
                <>
                  <div className={`${prefix}-column-history`}>
                    运行历史 &nbsp;
                    <StatusTag status={item.status} size={12} />
                  </div>
                  <div className={`${prefix}-column-audit`}>
                    <CheckBox
                      name="controlled"
                      onChange={handleChange}
                      checked={dyDetailStore.getAuditFlag}
                    >
                      待我审核
                    </CheckBox>
                  </div>
                  <div className={`${prefix}-column-lines`} />
                </>
              ) : <span />}
            </div>
            <div className={`${prefix}-column ${prefix}-column-notfirst`} onClick={handleClick(index, item.id)} style={getStyle(index)}>
              <div className={`${prefix}-column-number`}>
                {/* @ts-ignore */}
                <TreeItemName name={`#${item.viewId}` as any} headSpace={false} search="" />
                                   &nbsp;
              </div>
              <div className={`${prefix}-column-stage `}>
                {map(item.stageRecordList,
                  ({ status: stageStatus, triggerType: stageTriggerType = 'auto' }) => (
                    <>
                      <span className={`${prefix}-column-stage-line ${prefix}-column-stage-line-${stageTriggerType}`} />
                      <span className={`${prefix}-column-stage-item ${prefix}-column-stage-item-${stageStatus}`} />
                    </>
                  ))}
              </div>
              <UserInfo name={item?.trigger?.realName} url={item?.trigger?.imageUrl} email={item?.trigger?.email} />
              <TimePopover
                content={item.creationDate}
                style={timePopoverStyle}
              />
              {renderAction(item)}
            </div>
          </div>
        ))}
    </>
  );
};

export default observer(Index);
